<?php

namespace app\index\controller;

use app\CommonController;
use app\index\middleware\Auth;
use app\index\Validate\MemberValidate;
use app\model\Common;
use app\model\FinancialLog;
use app\model\MemberCoin;
use app\service\FinancialLogService;
use app\service\LetterService;
use app\service\MarketService;
use app\service\MemberCoinService;
use app\service\MemberService;
use app\service\PayCoinService;
use think\exception\ValidateException;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use app\model\Letter;

class Member extends CommonController
{

    protected $middleware = [Auth::class];
    const LevelMap = [
        1 => "一级代理",
        2 => "二级代理",
        3 => "三级代理"
    ];

    public function index()
    {
        $service = $this->app->make(MemberService::class);
        $member = $service->get($this->request->uid, ["audit_status", 'trade_passwd', 'customer_link', 'realname', 'idcard', 'id']);
        $this->assign("member", $member);
        $this->assign("customer_link", h_get_customer_url());
        $letterService = $this->app->make(LetterService::class);
        $count = $letterService->count(["member_id" => $this->request->uid, "read_status" => Letter::LETTER_STATUS_INACTIVE], "id");
        $this->assign("count", $count);
        return $this->fetch("index");
    }


    public function record()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $where = [["member_id", "=", $this->request->uid]];
            if (!empty($params["flow_type"])) {
                $flowType = $params["flow_type"];
                $where[] = ['flow_type', '=', $flowType];
            }
            $financialLogService = $this->app->make(FinancialLogService::class);
            $list = $financialLogService->getListWithOutCount($where, "*", ["coin"]);
            int_to_string($list, ['flow_type' => config("global.TRADE_LIST_MAP")]);
            $this->assign("list", $list);
            $content = $this->fetch("record-ajax", $list);
            $this->result(["data" => $content, "list" => $list]);
        } else {
            return $this->fetch("record");
        }
    }


    public function asset()
    {
        $mid = $this->request->uid;
        $memberCoinService = $this->app->make(MemberCoinService::class);
        $list = $memberCoinService->getListWithOutCount(["member_id" => $mid], "*", ["coin"]);
        $sum = 0;
        foreach ($list as $key => $val) {
            $total = h_money_switch($val["coin"]["coin_name"], $val["account_amount"] + $val["frozen_amount"]);
            $sum += $total;
            $list[$key]["usdt"] = $total;
        }
        $this->assign(compact("list", "sum"));
        return $this->fetch("asset");
    }


    public function changePasswd()
    {
        if ($this->request->post()) {
            $data = $this->request->post();
            try {
                validate(MemberValidate::class)->scene("changePasswd")->check($data);
            } catch (ValidateException $e) {
                throw new ValidateException($e->getError());
            }
            $memberService = $this->app->make(MemberService::class);
            $member = $memberService->getOne(["id" => $this->request->uid], "passwd");
            if (!$member || !password_verify($data["oldpasswd"], $member->passwd)) {
                $this->error("旧密码错误");
            }
            $member->passwd = $data["passwd"];
            $res = $member->save();
            if ($res) {
                $this->success("修改成功");
            } else {
                $this->error("修改失败");
            }
        } else {
            return $this->fetch("change-passwd");
        }
    }

    public function setWithdrawPasswd()
    {
        if ($this->request->post()) {
            $data = $this->request->post();
            try {
                validate(MemberValidate::class)->scene("setWithdrawPasswd")->check($data);
            } catch (ValidateException $e) {
                throw new ValidateException($e->getError());
            }
            $memberService = $this->app->make(MemberService::class);
            $member = $memberService->getOne(["id" => $this->request->uid], "trade_passwd");
            $member->trade_passwd = $data["passwd"];
            $res = $member->save();
            if ($res) {
                $this->success("修改成功");
            } else {
                $this->error("修改失败");
            }
        } else {
            return $this->fetch("set-withdraw-passwd");
        }

    }

    public function certificate()
    {
        if ($this->request->post()) {
            $data = $this->request->post();
            try {
                validate(MemberValidate::class)->scene("certificate")->check($data);
            } catch (ValidateException $e) {
                throw new ValidateException($e->getError());
            }
            $memberService = $this->app->make(MemberService::class);
            $member = $memberService->getOne(["id" => $this->request->uid], "realname,idcard,audit_status");
            $member->realname = $data["realname"];
            $member->idcard = $data["idcard"];
            $member->audit_status = \app\model\Member::MEMBER_AUDIT_STATUS_APPENDING;
            $res = $member->save();
            if ($res) {
                $this->success("认证成功");
            } else {
                $this->error("认证失败");
            }
        } else {
            return $this->fetch("certificate");
        }

    }

    public function invite()
    {
        $invitePath = $this->app->getRootPath() . "/public/static/index/images/tuiguang/" . $this->request->uid . ".png";
        $member = $this->app->make(MemberService::class);
        $market = $this->app->make(MarketService::class);
        if (!(dirname($invitePath))) {
            mkdir($invitePath, 0777);
        }
        $host = $this->request->host();
        $http = $this->request->scheme();
        $inviteCode = $member->value(["id" => $this->request->uid], "invite_code");
        $url = sprintf("%s://%s/login?invite=%s", $http, $host, $inviteCode);
        if (!file_exists($invitePath)) {
            $options = new QROptions([
                'version' => 6, // 二维码版本（1-40，版本越高容量越大、尺寸越大）
                'outputType' => QRCode::OUTPUT_IMAGE_PNG, // 输出格式：PNG（支持 PNG/JPG/SVG）
                'eccLevel' => QRCode::ECC_M, // 容错级别：M（15%容错，兼顾容量和抗损）
                'scale' => 8, // 缩放比例（值越大，二维码越清晰，文件也越大，建议 5-10）
                'margin' => 2, // 二维码边距（单位：像素，默认 4，可减小节省空间）
                'foregroundColor' => [0, 0, 0], // 前景色（黑色，RGB 值）
                'backgroundColor' => [255, 255, 255], // 背景色（白色，RGB 值）
                'height' => 200,
                'width' => 120
            ]);
            $qrcode = new QRCode($options);
            $qrcode->render($url, $invitePath);
        }
        $this->assign("uid", $this->request->uid);
        $firstTotal = $member->getLevelCount(1);
        $secondTotal = $member->getLevelCount(2);
        $thirdTotal = $member->getLevelCount(3);
        $firstLevelAsset = array_sum($member->getLevelSum(1));
        $secondLevelAsset = array_sum($member->getLevelSum(2));
        $thirdLevelAsset = array_sum($member->getLevelSum(3));
        $totalNum = $firstTotal + $secondTotal + $thirdTotal;
        $totalAsset = $firstLevelAsset + $secondLevelAsset + $thirdLevelAsset;
        $financialLogService = $this->app->make(FinancialLogService::class);
        $commisions = 0;
        $walletList = $financialLogService->getAll(
            [
                "member_id" => $this->request->uid,
                "flow_type" => FinancialLog::COMMISSION],
            "member_id,change_amount,coin_id");
        foreach ($walletList as $wallet) {
            $commisions += $market->getClosePriceByUsdt($wallet->coin_id, $wallet->change_amount);
        }
        $this->assign("url", $url);
        $this->assign(compact("firstTotal", "secondTotal", "thirdTotal", "firstLevelAsset", "secondLevelAsset", "thirdLevelAsset", "totalNum", "totalAsset", "commisions"));
        return $this->fetch("invite");
    }

    public function wallet()
    {
        $coinId = $this->request->post("coin_id");
        if (!$coinId) {
            $this->error("不存在的钱包");
        }
        $memberCoinService = $this->app->make(MemberCoinService::class);
        $payCoinService = $this->app->make(PayCoinService::class);
        $wallet = $memberCoinService->getOne(["member_id" => $this->request->uid, "coin_id" => $coinId], "coin_id,account_amount");
        if (empty($wallet)) {
            $this->result("", 100, "钱包不存在");
        }
        $payCoin = $payCoinService->get($coinId);
        if (empty($payCoin)) {
            $this->error("不存在的钱包");
        }
        $data = $wallet->toArray();
        $data["code"] = $payCoin->coin_name;
        $arr["data"] = $data;
        $this->result($arr);
    }

    public function agent()
    {
        // 非POST请求直接渲染页面
        if (!$this->request->isPost()) {
            $this->assign("level",$this->request->param("level",1));
            return $this->fetch("agent");
        }

        // 获取并验证层级参数
        $level = (int)$this->request->post("level", 1);
        if (!isset(self::LevelMap[$level])) {
            throw new \InvalidArgumentException("无效的代理层级");
        }

        // 获取代理列表
        $memberService = $this->app->make(MemberService::class);
        $list = $memberService->getLevelList($level, "id,email,audit_status,register_at,realname");

        // 处理充值金额数据
        if (!empty($list)) {
            $mids = array_column($list, "id");
            $memberCoinService = $this->app->make(MemberCoinService::class);
            $rechargeMap = $memberCoinService->getTotalRechargeByMid($mids) ?: [];

            // 关联充值金额（使用引用提高效率）
            foreach ($list as &$member) {
                $member["currency"] = $rechargeMap[$member["id"]] ?? 0;
            }
            unset($member); // 解除引用
        }

        // 渲染模板并返回结果
        $content = $this->fetch("agent-ajax", [
            "list" => $list,
            "level" => self::LevelMap[$level]
        ]);

        $this->result(["data" => $content]);

    }

}